package com.example.amap.tencent.map

import android.location.Location
import android.view.View
import com.example.amap.map.IMapView
import com.tencent.tencentmap.mapsdk.maps.LocationSource
import com.tencent.tencentmap.mapsdk.maps.MapView
import com.tencent.tencentmap.mapsdk.maps.model.MyLocationConfig

class TencentMapView(private val mapView: MapView?) : IMapView {

    private var locationChangedListener: LocationSource.OnLocationChangedListener? = null

    private val location = Location("LongPressLocationProvider")

    private val locationSource = object : LocationSource {
        override fun activate(p0: LocationSource.OnLocationChangedListener?) {
            locationChangedListener = p0
        }

        override fun deactivate() {
            locationChangedListener = null
        }
    }

    override fun getMapView(): View? {
        return mapView
    }

    override fun showMyLocationIcon() {
        mapView?.map?.apply {
            myLocationConfig = MyLocationConfig.newBuilder()
                .setMyLocationEnabled(true)
                .setLocationSource(locationSource)
                .build()
        }
    }

    override fun onLocationUpdate(lon: Double, lat: Double, dir: Float) {
        location.apply {
            latitude = lat
            longitude = lon
            if (!dir.isNaN() && dir in 0.0..360.0) {
                this.bearing = dir
            }
        }
        locationChangedListener?.onLocationChanged(location)
    }
}